package org.ploin.gui.model;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.ploin.persistence.entity.User;
import org.ploin.service.businesslogic.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;



@Component
@Scope("request")
public class LogInBean extends BaseBean {

	private static final long serialVersionUID = 199L;

    private SessionBean sessionBean;
    private ILoginService loginService;
	private String loginName = "admin";
	private String password;
	EntityManagerFactory entityManagerFactory;
	
	
	public String doLogin() {
		Context ctx;
		try {
			ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("jdbc/mysqltest");
			Connection con = ds.getConnection();
			System.out.print("uuuuuuuuuuuhuhuh"+con.createStatement());
			entityManagerFactory.createEntityManager().createQuery(" from Libro").getResultList();
		}
		catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		
		User user = null;
//		user = loginService.getByLoginInformation(loginName, password);
		if ("admin".equals(loginName) && "admin".equals(password)){
			user = new User();
			user.setUserName("admin");
			user.setFirstName("Admin");
			user.setLastName("Admin");
		}
		if (user == null) {
			addErrorMessage("ERROR.WRONG.LOGINDATA_"); // from resourceBundle
			// addErrorMessageText("ERROR", "Username or password wrong.");
			return null;
		}
		sessionBean.setUser(user);
		return "/page/welcome";
	}

	public SessionBean getSessionBean() {
		return sessionBean;
	}

	public void setSessionBean(SessionBean sessionBean) {
		this.sessionBean = sessionBean;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	@Autowired()
	public EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}
	
	

}
